<template>
  <div class="filters-container">
    <CloseOutlined class="close" @click="close" />
    <vue3-tree-org
      :data="list || ''"
      :node-draggable="false"
      :props="{ id: 'id', label: 'name', children: 'children', key: 'id' }"
      center
      :horizontal="true"
      :collapsable="false"
      @on-contextmenu="onMenus"
      @on-node-blur="onNodeBlur"
      @on-node-drag-end="onNodeDragEnd"
      @on-drag-stop="onDragstop"
    >
      <template #default="{ node }">
        <div v-if="node.$$data.isEdit" class="node-edit">
          <a-input-group compact>
            <a-input
              :value="node.$$data.value"
              @change="(val) => onNodeChange(node, val, 1)"
              style="width: 30%"
            />
            <a-input
              :value="node.$$data.name"
              @change="(val) => onNodeChange(node, val, 2)"
              style="width: 30%"
            />
            <a-button
              type="primary"
              style="width: 20%"
              @click="onNodeSave(node)"
              >保存</a-button
            >
            <a-button style="width: 20%" @click="onNodeRest(node)"
              >取消</a-button
            >
          </a-input-group>
        </div>
        <div
          v-else
          class="filters-node"
          style="
            padding: 10px;
            text-align: center;
            border-radius: 2px;
            box-shadow: 0 1px 5px rgba(0, 0, 0, 0.15);
            background: #fff;
          "
          :data-node="JSON.stringify(node)"
          draggable="move"
        >
          {{ node.$$data.name }}
        </div>
      </template>
    </vue3-tree-org>
  </div>
</template>
<script setup>
import Vue3TreeOrg from "vue3-tree-org";
import "vue3-tree-org/lib/vue3-tree-org.css";
import { CloseOutlined } from "@ant-design/icons-vue";
import { createFilter, editFilter, deleteFilter } from "@/api/designer/filters";
import Tool from "@/utils/tool";
import store from "@/store";

const emit = defineEmits(["close"]);
const vue3TreeOrg = Vue3TreeOrg.Vue3TreeOrg;

console.log(vue3TreeOrg, "vue3TreeOrg");

const list = ref({});
let EventStatus = "";

/**
 * 根据节点ID在树形结构中查找根节点
 * @param {Array} trees - 树形结构数组
 * @param {string|number} nodeIdToFind - 要查找的节点ID
 * @returns {Object|null} - 返回找到的根节点或null
 */
function findRootNodeById(trees, nodeIdToFind) {
  // 处理边界条件
  if (!Array.isArray(trees) || trees.length === 0) {
    return null;
  }

  for (const tree of trees) {
    const rootNode = tree;
    // 使用辅助函数在树中查找节点
    if (findNodeInTree(rootNode, nodeIdToFind)) {
      return rootNode;
    }
  }
  // 如果没有找到，返回null
  return null;
}

/**
 * 在树形结构中递归查找指定ID的节点
 * @param {Object} node - 当前节点
 * @param {string|number} idToFind - 要查找的节点ID
 * @returns {boolean} - 如果找到节点则返回true，否则返回false
 */
function findNodeInTree(node, idToFind) {
  // 类型检查
  if (!node || typeof node !== "object") {
    return false;
  }

  if (node.id === idToFind) {
    return node;
  }

  if (node.children && Array.isArray(node.children)) {
    for (const child of node.children) {
      const cnode = findNodeInTree(child, idToFind);
      if (cnode) {
        return cnode;
      }
    }
  }
  return false;
}

const addFilter = async (node) => {
  if (!node.name) return;
  const { code } = await createFilter({
    pid: node.pid,
    id: node.id,
    name: node.name,
    value: node.value,
  });
  return code === rescf.codeVal;
};

const modifyFilter = async (node) => {
  if (!node.name) return;
  const { code, data } = await editFilter({
    id: node.id,
    name: node.name,
    value: node.value,
  });
  return code === rescf.codeVal;
};

const delFilter = async (node) => {
  const { code } = await deleteFilter({
    id: node.id,
  });
  return code === rescf.codeVal;
};

const onMenus = ({ node, command }) => {
  console.log(node, command);
  EventStatus = command;
  switch (command) {
    case "add":
      console.log(node.$$data.children, "node");
      node.$$data.children[node.$$data.children.length - 1].isEdit = true;
      break;
    case "edit":
      node.$$data.isEdit = true;
      break;
    case "delete":
      delFilter(node.$$data);
      break;
  }
};

const onNodeDragEnd = (x, y) => {
  console.log(x, y);
};

const onNodeChange = (node, val, type) => {
  console.log(node, "onNodeChange");
  if (type === 1) {
    node.value = val.target.value;
    node.$$data.value = val.target.value;
  } else if (type === 2) {
    node.name = val.target.value;
    node.label = val.target.value;
    node.$$data.name = val.target.value;
    node.$$data.label = val.target.value;
  }
};

function findParentNodeById(tree, targetId, parent = null) {
  for (let node of tree) {
    if (node.id === targetId) {
      return parent;
    }
    if (node.children && node.children.length > 0) {
      const result = findParentNodeById(node.children, targetId, node);
      if (result) {
        return result;
      }
    }
  }
  return null;
}
const onNodeRest = (node) => {
  node.$$data.isEdit = false;
  const parent = findParentNodeById(list.value.children, node.id);
  console.log(parent, "parent");
  if (parent) {
    parent.children = parent.children.filter((item) => item.id !== node.id);
  }
};

const onNodeSave = async (node) => {
  const data = node.$$data;
  let res = false;
  if (EventStatus === "add") {
    res = await addFilter(data);
  } else if (EventStatus === "edit") {
    res = await modifyFilter(data);
  }

  if (res) {
    node.$$data.isEdit = false;
    store.dispatch("app/refetchAllFilters");
  }
};

const onDragStop = ({ x, y }) => {
  console.log(x, y);
};

const onNodeBlur = (node, data) => {};

const close = () => {
  emit("close");
};

const getList = async () => {
  let tree = store.state.app.filtersTree;
  console.log(tree, "tree");
  list.value = {
    id: 0,
    name: "全部",
    value: "all",
    children: tree,
  };
  console.log(list.value, "list.value");
};

getList();
</script>
<style scoped lang="scss">
:deep(.zm-tree-org) {
  background: none;
  padding: 15px 30px 15px 15px;
}
:deep(.tree-org-node__textarea) {
  display: none !important;
}
.node-edit {
  display: flex;
  align-items: center;
  width: 300px;
}

:deep(.horizontal .tree-org-node__children:before) {
  border-top: 1px solid var(--colorBorder);
}

.filters-container {
  width: calc(100% - 680px);
  height: calc(100% - 0px);
  background-color: var(--colorBgContainer);
  box-shadow: 0 1px 8px rgba(0, 0, 0, 0.15);
  border-radius: 5px;
  position: absolute;
  left: 0;
  top: 0px;
  z-index: 100;
  .close {
    position: absolute;
    right: 10px;
    top: 10px;
    cursor: pointer;
    font-size: 20px;
    z-index: 10;
  }
  .filters-node {
    padding: 10px;
    background: var(--colorBgLayout) !important;
  }
}
:deep(.zm-tree-handle .zm-tree-handle-item) {
  background: var(--colorBgLayout) !important;
  border: 1px solid var(--colorBorder);
}
</style>
